package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author 李旭
 * @date 2021/10/26 15:45
 * @Description: 订单微服务的监听器
 */
@SuppressWarnings("all")
@Component
public class OrderInfoListener {


    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RabbitService rabbitService;

    //取消订单
    @RabbitListener(queues = {MqConst.QUEUE_ORDER_CANCEL})
    public void cancelOrder(Long orderId, Message message, Channel channel) {
        try {
            System.out.println("接收到了订单的ID:" + orderId + ":时间：" + new Date());

            OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
            if (OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus())) {//防止 幂等性问题
                //关闭支付宝的交易接口  远程调用支付微服务  关闭过程中 有人正在付钱
                //判断是否关闭成功
                //发消息
                //只有在未支付的情况下 才可以取消订单  表示是用户未付才可以取消订单
                orderInfoService.updateOrderStatus(orderInfo.getId(),ProcessStatus.CLOSED);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //修改订单状态  订单支付成功
    @RabbitListener(bindings = {@QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            key = MqConst.ROUTING_PAYMENT_PAY
    )})
    public void updateOrderStatusById(Long orderId, Message message, Channel channel) {
        try {
            System.out.println("接收到的订单ID：" + orderId);
            //幂等性  没有
            orderInfoService.updateOrderStatus(orderId,ProcessStatus.PAID);
            //发消息
            // 订单微服务（订单主表 订单详情表）   发消息    库存微服务（库存工作单表、库存工作单详情表）
            Map initWareInfo = orderInfoService.initWareOrder(orderId);
            //   json格式字符串
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_WARE_STOCK,
                    MqConst.ROUTING_WARE_STOCK, JSONObject.toJSONString(initWareInfo));
            //改订单状态为 已通知库储
            orderInfoService.updateOrderStatus(orderId,ProcessStatus.NOTIFIED_WARE);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //接收库存系统扣减库存是否成功
    /**
     * orderId	订单系统的订单ID
     * status	状态： ‘DEDUCTED’  (已减库存)
     *         状态：  ‘OUT_OF_STOCK’  (库存超卖)
     *         {}
     */
    @RabbitListener(bindings = {@QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            key = MqConst.ROUTING_WARE_ORDER
    )})
    public void updateOrderStatus(String result, Message message, Channel channel) {
        try {
            System.out.println("接收到扣减库存是否成功：" + result);

            Map map = JSONObject.parseObject(result, Map.class);
            if("DEDUCTED".equals(map.get("status"))){
                //扣减库存成功  修改订单的状态
                //改订单状态为 待发货  Object --> Integer --> Long
                                  // Object --> String --> Long
                orderInfoService.updateOrderStatus(Long.parseLong(
                        String.valueOf(map.get("orderId"))),ProcessStatus.WAITING_DELEVER);
            }else{
                //库存超卖
                orderInfoService.updateOrderStatus(Long.parseLong(
                        String.valueOf(map.get("orderId"))),ProcessStatus.STOCK_EXCEPTION);
                //打印日志转人工

            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
